package com.eduhzy.ttw.clazz.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.clazz.R;
import com.eduhzy.ttw.clazz.R2;
import com.eduhzy.ttw.clazz.di.component.DaggerGroupReviewComponent;
import com.eduhzy.ttw.clazz.di.module.GroupReviewModule;
import com.eduhzy.ttw.clazz.mvp.contract.GroupReviewContract;
import com.eduhzy.ttw.clazz.mvp.model.entity.ClazzScoreData;
import com.eduhzy.ttw.clazz.mvp.model.entity.HomeData;
import com.eduhzy.ttw.clazz.mvp.model.entity.ReviewGroupData;
import com.eduhzy.ttw.clazz.mvp.model.entity.ReviewStudentData;
import com.eduhzy.ttw.clazz.mvp.presenter.GroupReviewPresenter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.decoration.GridSpacingItemDecoration;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.commonsdk.http.CommonApi;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.umeng.analytics.MobclickAgent;

import org.angmarch.views.NiceSpinner;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-12-5 15:35:22
 */
@Route(path = RouterHub.CLAZZ_GROUPREVIEWFRAGMENT)
public class GroupReviewFragment extends BaseFragment<GroupReviewPresenter> implements GroupReviewContract.View {

    HomeData mBean;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @BindView(R2.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;

    @Inject
    BaseQuickAdapter<ReviewGroupData, AutoBaseViewHolder> mAdapter;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @BindView(R2.id.spinner)
    NiceSpinner mSpinner;
    private BottomSheetDialog chooseDialog;
    private BaseQuickAdapter<ClazzScoreData, AutoBaseViewHolder> adapter;
    private BaseQuickAdapter<ReviewStudentData, AutoBaseViewHolder> chooseAdapter;
    private RecyclerView mChooseDialogList;
    private TabLayout tabs;
    private int teamType = 1;
    private QMUIEmptyView emptyView;
    private GridLayoutManager mChooseGridLayoutManager;
    private GridSpacingItemDecoration chooseDialogDecoration;
    String[] mTitles = new String[]{
            "表扬", "待改进"
    };
    private StringBuilder studentIds = null;
    private QMUIEmptyView chooseEmptyView;
    private BottomSheetDialog bottomSheetDialog;
    private RecyclerView mDialogList;
    private GridLayoutManager mGridLayoutManager;
    private QMUIRoundButton btn;

    public static GroupReviewFragment newInstance(HomeData bean) {
        GroupReviewFragment fragment = new GroupReviewFragment();
        fragment.setData(bean);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerGroupReviewComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .groupReviewModule(new GroupReviewModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.clazz_fragment_group_review, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        getData();
        mAdapter.setHeaderFooterEmpty(true, true);
        List<String> dataset = new LinkedList<>(Arrays.asList("通用分组", "我的分组"));
        mSpinner.attachDataSource(dataset);
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                teamType = i + 1;
                getData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        mRvList.setLayoutManager(mLayoutManager);
        mRvList.setAdapter(mAdapter);
        mSwipeLayout.setOnRefreshListener(() -> getData());
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ReviewGroupData data = mAdapter.getData().get(position);
            initChooseDialog(data);
        });
    }

    private void initChooseDialog(ReviewGroupData data) {
        if (chooseDialog == null) {
            chooseDialog = new BottomSheetDialog(getActivity());
            List<ReviewStudentData> lists = new ArrayList<>();
            View view = View.inflate(getActivity(), R.layout.clazz_review_choose_dialog, null);
            chooseEmptyView = view.findViewById(R.id.emptyView);
            TextView tvTitle = view.findViewById(R.id.tv_title);
            tvTitle.setText("点评" + data.getTeamName());
            btn = view.findViewById(R.id.btn_submit);
            mChooseDialogList = view.findViewById(R.id.recycler);
            mChooseGridLayoutManager = new GridLayoutManager(chooseDialog.getContext(), 4);
            chooseDialogDecoration = new GridSpacingItemDecoration(3, RxUtil.getAutoHeight(chooseDialog.getContext(), 20), true);
            mChooseDialogList.addItemDecoration(chooseDialogDecoration);
            mChooseDialogList.setLayoutManager(mChooseGridLayoutManager);
            if (chooseAdapter == null) {
                chooseAdapter = new BaseQuickAdapter<ReviewStudentData, AutoBaseViewHolder>(R.layout.clazz_rv_item_choose_item, lists) {
                    @Override
                    protected void convert(AutoBaseViewHolder helper, ReviewStudentData item) {
                        helper.setChecked(R.id.rb_check, item.isCheck());
                        Glide.with(chooseDialog.getContext())
                                .load(item.getStudentId() == 0 ? R.drawable.img_clazz : CommonApi.APP_AVATAR + item.getStudentId())
                                .apply(RequestOptions.placeholderOf(R.drawable.public_img_default).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL))
                                .into((ImageView) helper.getView(R.id.iv_icon));
                        helper.setText(R.id.tv_name, item.getStudentName());
                    }

                };
                mChooseDialogList.setAdapter(chooseAdapter);
                chooseDialog.setContentView(view);
            }
        }
        mPresenter.getTeamUser(data.getTeamId());
        btn.setOnClickListener((v) -> {
            studentIds = new StringBuilder();
            for (ReviewStudentData studentData : chooseAdapter.getData()) {
                if (studentData.isCheck())
                    studentIds.append(studentData.getStudentId() + ",");
            }
            chooseDialog.dismiss();
            if (ObjectUtils.isNotEmpty((studentIds.toString()))) {
                initDialog(data);
            } else {
                showMessage("请至少选择一个学生进行评分");
            }
        });
        chooseAdapter.setOnItemClickListener((adapter1, view1, position) -> {
            ReviewStudentData studentData = chooseAdapter.getData().get(position);
            studentData.setCheck(!studentData.isCheck());
            chooseAdapter.notifyItemChanged(position);
        });
        chooseDialog.show();

    }

    @Subscriber(tag = RouterHub.CLAZZ_GROUPREVIEWFRAGMENT)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.EDIT_GROUP_SUCCESS:
                getData();
                break;
            case EventBusTags.DELETE_REVIEW:
                if (ObjectUtils.isNotEmpty(tabs)) {
                    if (tabs.getTabAt(0).isSelected()) {
                        mPresenter.getEvaluateTagList(mBean.getClassId(), 1);
                    } else {
                        mPresenter.getEvaluateTagList(mBean.getClassId(), 2);
                    }
                }
                break;
            case EventBusTags.ADD_REVIEW:
                if (ObjectUtils.isNotEmpty(tabs)) {
                    if (tabs.getTabAt(0).isSelected()) {
                        mBean.setType(1);
                        mPresenter.getEvaluateTagList(mBean.getClassId(), 1);
                    } else {
                        mBean.setType(2);
                        mPresenter.getEvaluateTagList(mBean.getClassId(), 2);
                    }
                }
                break;
            default:
        }
    }

    private void initDialog(ReviewGroupData groupData) {
        if (ObjectUtils.isEmpty(bottomSheetDialog)) {
            List<ClazzScoreData> lists = new ArrayList<>();
            bottomSheetDialog = new BottomSheetDialog(getActivity());
            View view = View.inflate(getActivity(), R.layout.clazz_review_dialog, null);
            emptyView = view.findViewById(R.id.emptyView);
            tabs = view.findViewById(R.id.tabs);
            mDialogList = view.findViewById(R.id.recycler);

            mGridLayoutManager = new GridLayoutManager(bottomSheetDialog.getContext(), 3);
            GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(3, RxUtil.getAutoHeight(bottomSheetDialog.getContext(), 20), true);
            mDialogList.addItemDecoration(decoration);
            mDialogList.setLayoutManager(mGridLayoutManager);
            adapter = new BaseQuickAdapter<ClazzScoreData, AutoBaseViewHolder>(R.layout.clazz_review_item_score, lists) {
                @Override
                protected void convert(AutoBaseViewHolder helper, ClazzScoreData item) {
                    helper.setIsRecyclable(false);
                    if (!item.isEdit()) {
                        Glide.with(bottomSheetDialog.getContext())
                                .load(item.getIconUrl(mContext))
                                .into((ImageView) helper.getView(R.id.iv_icon));

                        if (item.getScoreType() == 1) {
                            helper.setText(R.id.btn_del, "+ " + item.getScore());
                        } else if (item.getScoreType() == 2) {
                            helper.setText(R.id.btn_del, "- " + item.getScore());
                        }
                        helper.setGone(R.id.btn_del, true);
                    } else {
                        Glide.with(bottomSheetDialog.getContext())
                                .load(item.getResIcon())
                                .into((ImageView) helper.getView(R.id.iv_icon));
                        helper.setGone(R.id.btn_del, false);
                    }
                    helper.setText(R.id.tv_name, item.getTitle());
                }

            };
            mDialogList.setAdapter(adapter);
            setDivider(tabs);
            for (String title : mTitles) {
                tabs.addTab(tabs.newTab().setText(title));
            }
            tabs.getTabAt(0).select();
            tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    adapter.getData().clear();
                    adapter.notifyDataSetChanged();
                    if (tab.getPosition() == 0) {
                        mBean.setType(1);
                        mPresenter.getEvaluateTagList(mBean.getClassId(), 1);
                    } else {
                        mBean.setType(2);
                        mPresenter.getEvaluateTagList(mBean.getClassId(), 2);
                    }
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });


            bottomSheetDialog.setContentView(view);
        }
        if (ObjectUtils.isEmpty(adapter.getData())) {
            mBean.setType(1);
            mPresenter.getEvaluateTagList(mBean.getClassId(), 1);
        }
        adapter.setOnItemClickListener((adapter1, view1, position) -> {
            ClazzScoreData data = adapter.getData().get(position);
            if (data.isEdit()) {
                ARouter.getInstance().build(RouterHub.CLAZZ_EDITREVIEWACTIVITY)
                        .withString(Intent.EXTRA_TITLE, "编辑点评")
                        .withParcelable(Constants.PARCELABLE_DATA, mBean)
                        .navigation(getActivity());
            } else {
                bottomSheetDialog.dismiss();
                MobclickAgent.onEvent(getActivity(),"ttw_class_review_start");
                mPresenter.scoreSave(studentIds.toString(), mBean.getClassId(), data.getTagId(), teamType, groupData.getTeamId());
            }
        });
        bottomSheetDialog.show();
    }


    private void setDivider(TabLayout tabs) {
        /*TabLayout中间分界线*/
        LinearLayout linearLayout = (LinearLayout) tabs.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(getActivity(),
                R.drawable.layout_divider_vertical));
        linearLayout.setDividerPadding(RxUtil.getAutoHeight(getActivity(), 20));
    }

    private void getData() {
        if (ObjectUtils.isNotEmpty(mBean)) {
            mPresenter.getTeamList(mBean.getClassId(), teamType);
        }
    }

    @Override
    public void setData(@Nullable Object data) {
        if (ObjectUtils.isNotEmpty(data)) {
            mBean = (HomeData) data;
        }
    }

    @Override
    public void showLoading() {
        mSwipeLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        mSwipeLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void update(List<ReviewGroupData> data) {
        if (ObjectUtils.isEmpty(data)) {
            data = new ArrayList<>();
        }
        mAdapter.setNewData(data);
        if (mAdapter.getFooterLayoutCount() > 0) {
            mAdapter.removeAllFooterView();
        }
        View footer = View.inflate(getActivity(), R.layout.clazz_review_group_footer, null);
        if (teamType == 1 && String.valueOf(mBean.getClassAdviser()).equals(SPUtils.getInstance().getString(Constants.USERID))) {
            mAdapter.addFooterView(footer);
            footer.setOnClickListener(view -> {
                ARouter.getInstance().build(RouterHub.CLAZZ_GROUPLISTACTIVITY)
                        .withString(Intent.EXTRA_TITLE, "通用分组")
                        .withParcelable(Constants.PARCELABLE_DATA, mBean)
                        .withInt(Constants.ROUTER_INTEGER, teamType)
                        .navigation(getActivity());
            });
        } else if (teamType == 2) {
            mAdapter.addFooterView(footer);
            footer.setOnClickListener(view -> {
                ARouter.getInstance().build(RouterHub.CLAZZ_GROUPLISTACTIVITY)
                        .withString(Intent.EXTRA_TITLE, "我的分组")
                        .withParcelable(Constants.PARCELABLE_DATA, mBean)
                        .withInt(Constants.ROUTER_INTEGER, teamType)
                        .navigation(getActivity());
            });
        }
    }

    @Override
    public void updateChooseDialog(List<ReviewStudentData> data) {
        chooseAdapter.setNewData(data);
    }

    @Override
    public void showDialogLoading() {
        emptyView.show(true);
    }

    @Override
    public void hideDialogLoading() {
        emptyView.hide();
    }

    @Override
    public void updateDialog(List<ClazzScoreData> data) {
        MobclickAgent.onEvent(getActivity(),"ttw_class_review_dialog");
        if (ObjectUtils.isNotEmpty(adapter)) {
            adapter.setNewData(data);
            ClazzScoreData edit = new ClazzScoreData();
            edit.setIconUrl(0);
            edit.setResIcon(R.drawable.img_bianji);
            edit.setTitle("编辑");
            edit.setEdit(true);
            adapter.addData(edit);
        }
    }


    @Override
    public void showChooseDialogLoading() {
        chooseEmptyView.show(true);
    }

    @Override
    public void hideChooseDialogLoading() {
        chooseEmptyView.hide();
    }
}